﻿using System.Text.RegularExpressions;
using Jayden.Dll.Web.Enums;

namespace Jayden.Dll.Web
{
	public class UserAgent
	{
		private string m_UserAgent;
		private UserAgentType m_Type;
		private MatchCollection m_Matches;
		private int m_MajorVersion = -1;

		public const string UserAgentPattern = @"\b\w*\/\d*\.?\d*\.?\d*\.?\d*\s*(\([^\(\)]*\))?";
		public static readonly Regex UserAgentRegex = new Regex(UserAgentPattern);

		public UserAgent(string userAgent)
		{
			m_Type = UserAgentType.Other;
			m_UserAgent = userAgent;
			if (userAgent == null)
				return;
			m_Matches = UserAgentRegex.Matches(userAgent);

			string ieToken = " MSIE ";
			foreach (Match match in m_Matches)
			{
				if (match.Value.Contains(ieToken))
				{
					m_Type = UserAgentType.InternetExplorer;
					string text = match.Value;
					int index = text.IndexOf(ieToken);
					int end = text.IndexOf(";", index + ieToken.Length);
					string version = text.Substring(index + ieToken.Length, end - (index + ieToken.Length));
					string[] versions = version.Split('.');
					m_MajorVersion = int.Parse(versions[0]);
				}
				else if (match.Value.Contains("Chrome"))
					m_Type = UserAgentType.Chrome;
				else if (match.Value.Contains("Firefox"))
					m_Type = UserAgentType.Firefox;
				else if (match.Value.Contains("Safari"))
					m_Type = UserAgentType.Safari;
				else if (match.Value.Contains("Opera"))
					m_Type = UserAgentType.Opera;
			}

		}

		public bool HasMajorVersion { get { return m_MajorVersion != -1; } }
		public int MajorVersion { get { return m_MajorVersion; } }
		public UserAgentType Type { get { return m_Type; } }
		public MatchCollection Matches { get { return m_Matches; } }
		public string UserAgentString { get { return m_UserAgent; } }

		public override string ToString() { return m_UserAgent; }
	}
}
